/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        return isBInternal(root).isBalanced;
    }
    public class ReturnType{
        boolean isBalanced;
        int height;
        ReturnType(boolean isBalanced, int height){
            this.isBalanced = isBalanced;
            this.height = height;
        }
    }
    public ReturnType isBInternal(TreeNode root){
        if(root == null){
            return new ReturnType(true, 0);
        }
        ReturnType left = isBInternal(root.left);
        ReturnType right = isBInternal(root.right);
        int height = Math.max(left.height + 1, right.height + 1);
        boolean isBalanced = left.isBalanced && right.isBalanced
            && (Math.abs(left.height - right.height) <= 1);
        return new ReturnType(isBalanced, height);
    }
}